/*
 * Copyright (c) 2020-2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import ts from "typescript";
import allModules from "../rules/index.js";

const processArkUiCode = (code, rule) => {
  const resultFile = ts.createSourceFile(
    "index.ts",
    code,
    ts.ScriptTarget.Latest,
    true
  );
  const func = allModules[rule];
  return func(resultFile);
};

const processTSRule = ({ curTsRules, checkItems, file, code }) => {
  for (const rule of curTsRules) {
    const result = processArkUiCode(code, rule.checker);
    const filterResult = [];
    const map = new Map();
    for (const item of result) {
      if (!map.has(item.line)) {
        filterResult.push(item);
        map.set(item.line, 1);
      }
    }
    if (filterResult.length > 0) {
      const content = code.split("\n");
      for (const item of filterResult) {
        const info = {
          analyzerName: "apiengine",
          buggyFilePath: file,
          codeContextStartLine: item.line + 1,
          defectLevel: rule.severity,
          defectType: rule.checker,
          description: rule.description,
          mainBuggyCode: content[item.line],
          mainBuggyLine: item.line + 1,
          nodeList: item.nodeList,
        };
        checkItems.push(info);
      }
    }
  }
};

export { processTSRule };
